const http = require("http");
const fs = require('fs');
const path = require('path');
const Mock = require('./mock.js');

const jsonStr = fs.readFileSync(path.resolve(__dirname, `${__dirname.substring(__dirname.lastIndexOf(path.sep) + 1)}.json`), { encoding: 'utf8' });
const json = JSON.parse(jsonStr);
try {
  if (json.javascript) eval(json.javascript);
} catch (e) {
  console.log(`<span style='color:red;'>${e}</span>`);
  return;
}

const server = http.createServer();
server.on("request", function (request, response) {
  const url = request.url;
  const method = request.method;
  const data = {
    code: 404,
    url: url,
    type: method,
    msg: '该请求未匹配到该项目请求前缀',
    result: null
  };
  let result = null;
  let Return_Property = undefined;		  //是否要选择工具中定义的json中的某个一级字段作为返回对象
  let Return_Direct = undefined;		    //直接返回标志，不构造data结构
  let Return_Content_Type = undefined;	//默认返回json格式，其他格式请在工具中定义

  if (url.indexOf(json.baseUrl) > -1) {
    const u = url.replace(json.baseUrl, "");
    const api = json.mocks.string[u];
    if (api) {
      if (api.type.indexOf(method.toUpperCase()) > -1) {
        try {
          if (api.javascript) {
            eval(api.javascript);
            result = Mock.mock(api.template);
            if (Return_Property) {
              result = result[Return_Property];
              Return_Property = undefined;
            }
          } else {
            result = Mock.mock(api.template);
          }
          Object.assign(data, {
            code: 200,
            msg: '请求成功',
            result: result
          });
        } catch (e) {
          console.log("<span style='color:red'>" + e + "</span><br>");
          Object.assign(data, {
            code: 500,
            msg: "服务器端错误"
          });
        }
      } else {
        Object.assign(data, {
          code: 406,
          msg: `该请求不存在 ${method.toUpperCase()} 方法`
        });
      }
    } else {
      let index = -1;
      for (let i = 0, len = json.mocks.regx.length; i < len; i++) {
        if (eval(json.mocks.regx[i].url).test(u)) {
          index = i;
          break;
        }
      }
      if (index !== -1) {
        const api = json.mocks.regx[index];
        // console.log(api.type, method, api.type.indexOf(method.toUpperCase()));
        if (api.type.indexOf(method.toUpperCase()) > -1) {
          try {
            if (api.javascript) {
              eval(api.javascript);
              result = Mock.mock(api.template);
              if (Return_Property) {
                result = result[Return_Property];
                Return_Property = undefined;
              }
            } else {
              result = Mock.mock(api.template);
            }
            Object.assign(data, {
              code: 200,
              msg: '请求成功',
              result: result
            });
          } catch (e) {
            console.log("<span style='color:red'>" + e + "</span><br>");
            Object.assign(data, {
              code: 500,
              msg: "服务器端错误"
            });
          }
        } else {
          Object.assign(data, {
            code: 406,
            msg: `该请求不存在 ${method.toUpperCase()} 方法`
          });
        }
      } else {
        Object.assign(data, {
          code: 405,
          msg: '该请求未匹配到接口地址'
        });
      }
    }
  }
  if (Return_Content_Type) {
    response.writeHead(200, { 'Content-Type': Return_Content_Type, "Access-Control-Allow-Origin": "*" });
    Return_Content_Type = undefined;
  } else {
    response.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8', "Access-Control-Allow-Origin": "*" });
  }
  let dataStr = "";
  if (Return_Direct) {
    Return_Direct = undefined;
    dataStr = JSON.stringify(data.result);
  } else {
    dataStr = JSON.stringify(data);
  }
  response.end(dataStr, 'utf8');
  console.log(dataStr + "<br>");
});
server.listen(parseInt(json.port), json.host, function () {
  console.log(`host: ${json.host}<br>post: ${json.port}<br>baseUrl: ${json.baseUrl}<br>`);
  console.log("服务启动成功...<br>");
});

/**
 * data = {
 *   code: xxx,
 *   msg: 'xxxxxx',
 *   result: ...
 * }
 * code: {
 *   200: 完全成功，此时会有一个result字段
 *   404: 未匹配到baseUrl
 *   405: 匹配到baseUrl，但是位匹配到api url
 *   406: 匹配到url，但是未匹配到method
 *   500: 服务器端错误
 * }
 */
